package icu.luoxi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.luoxi.utils.ClassUtils;
import icu.luoxi.utils.SHA256Utils;
import icu.luoxi.utils.TokenUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import icu.luoxi.service.UserService;
import icu.luoxi.model.entity.User;
import icu.luoxi.common.BaseResponse;
import icu.luoxi.common.ErrorCode;
import icu.luoxi.common.ResultUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 洛希极限
 * @since 2025-03-31
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 注册
     * @param user 实体对象
     * @return 注册结果，注册成功返回id
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public BaseResponse save(@RequestBody User user) {
        String id = userService.createUser(user);
        if (id != null){
            return ResultUtils.success(id);
        }else {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 更新保存
     * @param userList 实体对象列表
     * @return 保存结果
     */
    @ApiOperation(value = "列表更新")
    @PostMapping("/batchUpsert")
    public BaseResponse upsertByList(@RequestBody List<User> userList) {
        boolean upsert = userService.saveOrUpdateBatch(userList);
        if (upsert){
            return ResultUtils.success("操作成功");
        }else {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 根据id主键批量删除
     * @param ids 主键列表
     * @return 删除结果
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping("/delByList")
    public BaseResponse delByList(@RequestBody List<String> ids) {
        boolean del = userService.removeByIds(ids);
        if (del){
            return ResultUtils.success("删除成功");
        }else {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 列表查询
     * @return 列表结果
     */
    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public BaseResponse<List<User>> findAll() {
        List<User> userList = userService.list();
        return ResultUtils.success(userList);
    }

    /**
     * 查询当前登录用户信息
     * @param token 用户登录后获取的token
     * @return 单条记录结果
     */
    @ApiOperation(value = "token获取用户信息")
    @GetMapping("/findOne")
    public BaseResponse<User> findOne(@RequestParam String token) {
        String username = TokenUtils.getUsernameFromToken(token);
        User user = new User();
        user.setUsername(username);
        return ResultUtils.success(userService.getOne(new QueryWrapper<>(user)));
    }

    /**
     *  分页查询
     * @param pageNum 页码
     * @param pageSize 尺寸
     * @return 分页查询结果
     */
    @ApiOperation(value = "分页查询")
    @GetMapping("/page")
    public BaseResponse<Page<User>> page(@RequestParam Integer pageNum,
                                         @RequestParam Integer pageSize,
                                         @RequestParam(required = false) String sortField,
                                         @RequestParam(required = false) String sortOrder,
                                         @RequestParam(required = false) String username,
                                         @RequestParam(required = false) String nickname) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(username!=null,"username",username);
        queryWrapper.like(nickname!=null,"nickname",nickname);
        OrderItem orderItem = new OrderItem();
        if(sortField != null && sortOrder != null){
            orderItem.setColumn(ClassUtils.getDbColumn(User.class,sortField));
            if("ascending".equals(sortOrder)){
                orderItem.setAsc(true);
            }else {
                orderItem.setAsc(false);
            }
        }
        return ResultUtils.success(userService.page(new Page<User>(pageNum, pageSize).addOrder(orderItem),queryWrapper));
    }

    /**
     * 登录
     * @param user 接收登录名和密码
     * @return 登录结果
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public BaseResponse login(@RequestBody User user){
        String token;
        String passWord = user.getPassword();
        user.setPassword(SHA256Utils.encrypt(passWord));
        User one = userService.getOne(new QueryWrapper<>(user));
        if(one==null){
            return ResultUtils.error(ErrorCode.USER_OR_PWD_ERROR);
        }else {
            token = TokenUtils.sign(user);
        }
        return ResultUtils.success(token);
    }
}

